/*
 * @Descripttion: 
 * @Author: 21070032
 * @Date: 2021-08-31 09:51:41
 * @LastEditors: 21070032
 * @LastEditTime: 2021-08-31 13:43:53
 */
const Router = require('koa-router');
const router = new Router();
const config = require('../config')
const fs = require('fs')

router.get('/pdf', async (ctx) => {
    const id = ctx.query.id
    const fileName = id + '.pdf'
    // 检查文件是否存在于当前目录中。
    if (fs.existsSync(`${config.uploadPath}/pdf/${fileName}`)) {
        return ctx.body = `${config.uploadExport}/pdf/${fileName}`
    } else {
        // await generatePdf(ctx.access_token, id, `/pdf/${fileName}`);
        // return ctx.body = `${config.uploadExport}/pdf/${fileName}`
    }

})
router.get('/', async ctx => {
    const { get } = require('../models/quotation');
    const res = await get(ctx.access_token, ctx.query)
    ctx.errcode(res.data.errcode, res.data.errmsg)

    ctx.body = {
        code: 200,
        data: {
            ...res.data,
            data: res.data.data.map(item => JSON.parse(item)),
        },
        msg: 'ok'
    };
})
router.get('/:id', async ctx => {
    const { getInfo } = require('../models/quotation');
    const res = await getInfo(ctx.access_token, ctx.params.id)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: (res.data.data.map(item => JSON.parse(item)))[0],
        msg: 'ok'
    };
})
router.post('/', async ctx => {
    const { add } = require('../models/quotation');
    const res = await add(ctx.access_token, ctx.request.body)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})
router.delete('/', async ctx => {
    const { del } = require('../models/quotation');
    const res = await del(ctx.access_token, ctx.query.id)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})
router.put('/', async ctx => {
    const { update } = require('../models/quotation');
    const res = await update(ctx.access_token, ctx.request.body)
    console.log(res.data)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})

module.exports = router.routes();